package com.sakura.order.servie.impl;

import com.sakura.order.entity.Order;
import com.sakura.order.feign.ProductFeignService;
import com.sakura.order.feign.StockFeignService;
import com.sakura.order.mapper.OrderMapper;
import com.sakura.order.params.AddOrderParams;
import com.sakura.order.servie.OrderService;
import lombok.extern.java.Log;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Log
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    StockFeignService stockFeignService;


    @Override
    public String addOrder(AddOrderParams params) {
        Integer num = stockFeignService.getProductNum(params.getProductNo());
        log.info("商品库存数量：" + num);
        if (num == null || num < 1 || num < params.getNum()) {
            return "商品库存不足";
        }

        Order order = new Order();

        // 根据当前日期加随机数生成一个订单号
        order.setOrderNo(DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS")
                + (int) ((Math.random() * 9 + 1) * 10000000));
        order.setProductNo(params.getProductNo());
        order.setNum(params.getNum());

        // 去商品服务获取商品单价
        Integer unitPrice = productFeignService.getUnitPrice(params.getProductNo());
        log.info("商品单价：" + unitPrice);
        if (unitPrice == null || unitPrice < 0) {
            return "商品价格异常";
        }
        order.setTotalPrice(params.getNum() * unitPrice);
        order.setStatus(1);
        orderMapper.insert(order);

        String productName = productFeignService.getProductName(params.getProductNo());


        return "商品下单成功，订单ID：" + order.getOrderNo() +", 订单名称："+productName+ ", 库存：" + num + " 单价：" + unitPrice;
    }
}
